package tree;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class constructMaximumBinaryTree {
    Map<Integer, Integer> map;
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        return buildMaxTree(nums, 0, nums.length);
    }
    public TreeNode buildMaxTree(int[] nums, int begin, int end){
        if (begin >= end){
            return null;
        }
//        int max = Arrays.stream(nums, begin, end)
//                .max()
//                .getAsInt();
        int max = Integer.MIN_VALUE;
        for (int i = begin; i < end; i++) {
            if (nums[i] > max){
                max = nums[i];
            }
        }
        int rootIndex = map.get(max);
        int len = rootIndex - begin;
        TreeNode root = new TreeNode(max);
        root.left = buildMaxTree(nums, begin, begin + len);
        root.right = buildMaxTree(nums, rootIndex + 1, end);
        return root;
    }
}
